package com.ithl.edumsm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ithl.edumsm.service.MsmService;
import com.ithl.serviceutils.exchandler.MyException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author hl
 * @Data 2020/4/22
 */
@Service
public class MsmServiceImpl implements MsmService {

    // 发送短信
    @Override
    public boolean sendMessage(Map<String, Object> param, String phone) {
        if (StringUtils.isEmpty(phone)) return false;
        // 1. 地域节点 2. oss keyid 3.密钥
        DefaultProfile defaultProfile = DefaultProfile.getProfile("default", "LTAI4G9qTMpZUXiTFFb6NpTc", "K8VVKnc6BwkWc8QF4QF3uIbk5EiTJy");
        IAcsClient client = new DefaultAcsClient(defaultProfile);
        // 设置相关固定参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 设置发送相关参数
        request.putQueryParameter("PhoneNumbers", phone); // 电话号码
        request.putQueryParameter("SignName", "我的在线教育网站"); // 签名名称
        request.putQueryParameter("TemplateCode", "SMS_188631743"); // 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); // 验证码参数(转换为json)
        try {
            CommonResponse response = client.getCommonResponse(request);
            boolean isSuccess = response.getHttpResponse().isSuccess();
            return isSuccess;
        } catch (Exception e) {
            throw new MyException(1, e.getMessage());
        }
    }
}
